<template>
  <view class="container">
    <!-- 风格/主题 -->
    <view class="section style-section" v-if="outfit.style">
      <text class="style-text">风格: {{ outfit.style }}</text>
    </view>
    
    <!-- 衣物列表部分 -->
    <view class="clothes-list-section">
      <view class="section-title">搭配详情</view>
      <view v-if="clothesItems && clothesItems.length > 0">
        <view 
          v-for="(item, itemIndex) in clothesItems" 
          :key="'item-' + itemIndex"
          class="clothes-item"
          @click="navigateToDetail(item)"
        >
          <image :src="item.image_url" class="clothes-image" mode="aspectFill" @error="handleImageError($event, item)"></image>
          <view class="clothes-info">
            <text class="category-text">{{ item.category }}</text>
            <text class="subcategory-text">{{ item.subcategory }}</text>
          </view>
          <view class="arrow-icon">
            <uni-icons type="right" size="20" color="#666"></uni-icons>
          </view>
        </view>
      </view>
      <view v-else class="empty-state">
        <text>暂无衣物数据</text>
      </view>
    </view>
    
    <!-- 评分部分 -->
    <view class="section rating-section">
      <view class="rating-title">评分:</view>
      <uni-rate 
        :value="outfit.rating" 
        :size="32" 
        :margin="15" 
        :is-fill="false"
        active-color="#FFC90E"
        :readonly="true"
      ></uni-rate>
    </view>
    
    <!-- 详细搭配信息 -->
    <view class="detail-section">
      <!-- 搭配季节 -->
      <view class="detail-item" v-if="outfit.seasons">
        <text class="detail-title">搭配季节：</text>
        <view class="season-tags">
          <view 
            v-for="(season, index) in seasonsArray" 
            :key="index" 
            class="season-tag"
          >
            {{ season }}
          </view>
        </view>
      </view>
      
      <!-- 搭配标签 -->
      <view class="detail-item" v-if="outfit.tags">
        <text class="detail-title">搭配标签：</text>
        <view class="custom-tags">
          <view v-for="(tag, index) in tagsArray" :key="index" class="custom-tag">
            {{ tag }}
          </view>
        </view>
      </view>
      
      <!-- 适合场景 -->
      <view class="detail-item" v-if="outfit.scenes">
        <text class="detail-title">适合场景：</text>
        <view class="scene-tags">
          <view v-for="(scene, index) in scenesArray" :key="index" class="scene-tag">
            {{ scene }}
          </view>
        </view>
      </view>
      
      <!-- 适穿温度/天气 -->
      <view class="detail-item" v-if="outfit.weather_info">
        <text class="detail-title">适穿温度/天气：</text>
        <view class="weather-info">
          <template v-if="weatherInfo.type === 'weather'">
            <text>温度: {{ weatherInfo.temperature }}°C</text>
            <text>天气: {{ weatherInfo.condition }}</text>
            <text v-if="weatherInfo.winddirection">风向: {{ weatherInfo.winddirection }}</text>
            <text v-if="weatherInfo.windpower">风力: {{ weatherInfo.windpower }}级</text>
            <text v-if="weatherInfo.humidity">湿度: {{ weatherInfo.humidity }}%</text>
          </template>
          <template v-else-if="weatherInfo.type === 'temperature_range'">
            <text>温度范围: {{ weatherInfo.min || '?' }}°C ~ {{ weatherInfo.max || '?' }}°C</text>
          </template>
        </view>
      </view>
      
      <!-- 创建日期 -->
      <view class="detail-item">
        <text class="detail-title">创建日期：</text>
        <text class="date-text">{{ formatDate(outfit.feedback_time) }}</text>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="action-button delete-button" @click="deleteOutfit">
          <uni-icons type="trash" size="20" color="#f44336"></uni-icons>
          <text>删除搭配</text>
        </button>
        
        <button class="action-button share-button" @click="shareOutfit">
          <uni-icons type="redo" size="20" color="#4caf50"></uni-icons>
          <text>分享搭配</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import setting from "../../setting"

export default {
  data() {
    return {
      outfit: {
        outfit_id: null,
        user_id: null,
        rating: 0,
        seasons: "",
        tags: "",
        scenes: "",
        style: "",
        weather_info: "",
        feedback_time: null,
      },
      clothesItems: [],
      outfitId: null,
    }
  },

  computed: {
    seasonsArray() {
      return this.outfit.seasons ? this.outfit.seasons.split(",") : []
    },
    tagsArray() {
      return this.outfit.tags ? this.outfit.tags.split(",") : []
    },
    scenesArray() {
      return this.outfit.scenes ? this.outfit.scenes.split(",") : []
    },
    weatherInfo() {
      try {
        return this.outfit.weather_info ? JSON.parse(this.outfit.weather_info) : {}
      } catch (e) {
        console.error("解析天气信息失败:", e)
        return {}
      }
    },
  },

  onLoad(options) {
    if (options.outfit_id) {
      this.outfitId = options.outfit_id
      this.loadOutfitDetails()
    } else {
      uni.showToast({
        title: "缺少搭配ID",
        icon: "none",
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },

  methods: {
    // 格式化图片URL - 使用与衣柜组件相同的逻辑
    formatImageUrl(url) {
      if (!url) return ""

      // 处理不同类型的URL
      if (url.startsWith("blob:")) {
        // blob URL 可能已经失效，需要特殊处理
        // 尝试从服务器获取图片 - 假设图片名称在URL的最后部分
        const filename = url.split("/").pop()
        if (filename) {
          const serverUrl = `${setting.url}/uploads/clothes/${filename}`
          return serverUrl
        }
        return url // 如果无法提取文件名，保留原始URL
      } else if (url.startsWith("/uploads/")) {
        // 服务器上的图片添加服务器地址前缀
        const formattedUrl = `${setting.url}${url}`
        return formattedUrl
      } else if (!url.startsWith("http") && !url.startsWith("/static/")) {
        // 其他相对路径情况
        const formattedUrl = `${setting.url}/uploads/clothes/${url}`
        return formattedUrl
      }

      // 已经是完整URL
      return url
    },

    // 处理图片加载错误
    handleImageError(e, item) {
      //console.error(`图片加载失败: ${item.image_url}`, e)
      
      // 保存原始URL
      if (!item._originalUrl) {
        item._originalUrl = item.image_url
      }
      
      // 尝试不同的URL格式
      if (item.image_url.startsWith("blob:")) {
        // 如果是blob URL失败，尝试从服务器获取
        const filename = item._originalUrl.split("/").pop()
        if (filename) {
          item.image_url = `${setting.url}/uploads/clothes/${filename}`  
        } else {
          // 如果无法提取文件名，尝试使用ID作为文件名
          item.image_url = `${setting.url}/uploads/clothes/${item.clothes_id}.jpg`
        }
      } else if (item.image_url.includes("/uploads/")) {
        // 如果服务器路径失败，尝试直接使用文件名
        const filename = item.image_url.split("/").pop()
        item.image_url = `${setting.url}/uploads/clothes/${filename}`
      } else if (!item.image_url.startsWith("/static/")) {
        // 尝试使用静态资源路径
        item.image_url = "/static/default-clothes.png" 
      }
      
      // 强制更新视图
      this.$forceUpdate()
    },

    // 加载搭配详情
    loadOutfitDetails() {
      uni.showLoading({
        title: "加载中...",
      })

      uni.request({
        url: `${setting.url}/api/outfit_detail?outfit_id=${this.outfitId}`,
        method: "GET",
        success: (res) => {
          if (res.statusCode === 200 && res.data.outfit) {
            this.outfit = res.data.outfit

            // 处理衣物列表，但不在这里处理图片URL
            // 而是在模板中使用formatImageUrl方法
            this.clothesItems = res.data.clothes_items || []

            console.log("加载的搭配详情:", this.outfit)
            console.log("加载的衣物列表:", this.clothesItems)
          } else {
            uni.showToast({
              title: "获取搭配详情失败",
              icon: "none",
            })
          }
        },
        fail: (err) => {
          console.error("请求失败:", err)
          uni.showToast({
            title: "网络请求失败",
            icon: "none",
          })
        },
        complete: () => {
          uni.hideLoading()
        },
      })
    },

    // 导航到衣物详情页
    navigateToDetail(item) {
      if (!item.clothes_id) {
        uni.showToast({ title: "衣物数据异常", icon: "none" })
        return
      }
      uni.navigateTo({
        url: `../ClothesDetail/ClothesDetail?id=${item.clothes_id}`,
      })
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "未知日期"

      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`
    },

    // 删除搭配
    deleteOutfit() {
      uni.showModal({
        title: "确认删除",
        content: "确定要删除这套搭配吗？删除后无法恢复。",
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: "删除中...",
            })

            uni.request({
              url: `${setting.url}/api/delete_outfit`,
              method: "POST",
              data: {
                outfit_id: this.outfitId,
                user_id: this.outfit.user_id,
              },
              success: (res) => {
                if (res.statusCode === 200) {
                  uni.showToast({
                    title: "删除成功",
                    icon: "success",
                  })

                  // 返回上一页
                  setTimeout(() => {
                    uni.navigateBack()
                  }, 1500)
                } else {
                  uni.showToast({
                    title: "删除失败: " + (res.data.error || "未知错误"),
                    icon: "none",
                  })
                }
              },
              fail: (err) => {
                console.error("请求失败:", err)
                uni.showToast({
                  title: "网络请求失败",
                  icon: "none",
                })
              },
              complete: () => {
                uni.hideLoading()
              },
            })
          }
        },
      })
    },

    // 分享搭配
    shareOutfit() {
      uni.showToast({
        title: "分享功能开发中",
        icon: "none",
      })
    },
  },
}
</script>
<style>
.container {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  height: 100vh;
  justify-content: space-between;
  overflow-y: auto;
  box-sizing: border-box;
  background-color: #f9f9f9;
}

.section {
  margin-bottom: 40rpx;
  justify-content: space-between;
  overflow: hidden;
}

.style-section {
  border: thick double #FFC90E;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.style-text {
  font-size: 36rpx;
  color: #333;
  font-weight: 600;
}

/* 衣物列表样式 */
.clothes-list-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.clothes-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #fff;
  border-radius: 8rpx;
  margin-bottom: 10rpx;
}

.clothes-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  object-fit: cover;
  margin-right: 20rpx;
}

.clothes-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.category-text {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.subcategory-text {
  font-size: 26rpx;
  color: #666;
}

.arrow-icon {
  margin-left: 20rpx;
}

.empty-state {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

/* 评分部分样式 */
.rating-section {
  display: flex;
  flex-direction: row;
  min-height:80rpx;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.rating-title {
  font-size: 32rpx;
  margin-right: 20rpx;
  color: #333;
  font-weight: bold;
}

/* 详细信息部分样式 */
.detail-section {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  margin-bottom: 40rpx;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  padding: 24rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  border-left: 8rpx solid #FFC90E;
}

.detail-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  border-bottom: 2rpx dashed #eaeaea;
  padding-bottom: 12rpx;
}

.season-tags, .custom-tags, .scene-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  padding: 10rpx 0;
}

.season-tag {
  padding: 10rpx 24rpx;
  border: 1px solid #FFC90E;
  border-radius: 30rpx;
  font-size: 28rpx;
  color: #333;
  background-color: rgba(255, 201, 14, 0.1);
  box-shadow: 0 2rpx 6rpx rgba(255, 201, 14, 0.2);
}

.custom-tag {
  padding: 10rpx 24rpx;
  background-color: #f0f0f0;
  border-radius: 30rpx;
  font-size: 28rpx;
  color: #333;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
}

.scene-tag {
  padding: 10rpx 24rpx;
  border: 1px solid #4caf50;
  border-radius: 30rpx;
  font-size: 28rpx;
  color: #333;
  background-color: rgba(76, 175, 80, 0.1);
  box-shadow: 0 2rpx 6rpx rgba(76, 175, 80, 0.2);
}

.weather-info {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  font-size: 28rpx;
  padding: 10rpx 0;
}

.weather-info text {
  padding: 10rpx 20rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  border: 1rpx solid #eaeaea;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
}

.date-text {
  font-size: 28rpx;
  color: #666;
  padding: 10rpx 0;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  margin-top: 20rpx;
}

.action-button {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 24rpx 20rpx;
  font-size: 30rpx;
  font-weight: 500;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  border: none;
  position: relative;
  overflow: hidden;
}

.action-button:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.delete-button {
  color: #f44336;
  border-left: 8rpx solid #f44336;
}

.delete-button::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(244, 67, 54, 0.08);
  z-index: -1;
}

.share-button {
  color: #4caf50;
  border-left: 8rpx solid #4caf50;
}

.share-button::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(76, 175, 80, 0.08);
  z-index: -1;
}
</style>
